package org.esprit.ocm.client.ui.ec2;

import org.esprit.ocm.client.rpc.ec2.KeyPairServiceAsync.Util;
import org.esprit.ocm.dto.ec2.impl.KeyPairInfoMappingDto;
import org.esprit.ocm.dto.impl.AwsCredentialsDto;
import org.esprit.ocm.dto.impl.ServerDto;
import org.esprit.ocm.dto.impl.UserDto;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.types.VerticalAlignment;
import com.smartgwt.client.widgets.Window;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.fields.ButtonItem;
import com.smartgwt.client.widgets.form.fields.TextItem;
import com.smartgwt.client.widgets.form.fields.events.ClickEvent;
import com.smartgwt.client.widgets.form.fields.events.ClickHandler;

public class AddKeyPair extends Window {

	public AddKeyPair(final ServerDto server, final AwsCredentialsDto credentials, final UserDto user) {
		setTitle("Add KeyPair");
		setWidth(250);
		setHeight(150);
		setIsModal(true);
		setShowModalMask(true);
		setShowCloseButton(true);
		centerInPage();

		final DynamicForm formKeyPair = new DynamicForm();
		formKeyPair.setWidth(100);
		formKeyPair.setHeight(100);
		formKeyPair.setPadding(5);
		formKeyPair.setLayoutAlign(VerticalAlignment.TOP);

		final TextItem name = new TextItem("name");
		name.setTitle("name");
		name.setRequired(true);

		ButtonItem createButton = new ButtonItem("create", "Create");
		createButton.setAlign(Alignment.CENTER);
		createButton.addClickHandler(new ClickHandler() {

			public void onClick(ClickEvent event) {

				Util.getInstance().createKeypair(name.getValue().toString(), server, credentials, new AsyncCallback<KeyPairInfoMappingDto>() {

					public void onSuccess(KeyPairInfoMappingDto k) {
						// TODO Auto-generated method stub

						hide();
						GenerateKeyPair generateKey = new GenerateKeyPair(server, credentials, user, k);
						generateKey.show();
					}

					public void onFailure(Throwable arg0) {
						// TODO Auto-generated method stub

					}
				});
			}
		});

		formKeyPair.setFields(name, createButton);
		formKeyPair.redraw();

		addItem(formKeyPair);

		draw();
	}

}
